﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace AlgorithmExercise.Introduction
{
    /// <summary>
    /// 二进制数组相加。
    /// 两个N位的二进制整数（分别存储在两个长度为N的数组A和B中）加起来，存储在一个长度为N=1的数组C中；
    /// </summary>
    public class BinaryAdd
    {
        const int N = 8;

        public BinaryAdd()
        {
            var random = new Random();
            byte[] A = new byte[N];
            byte[] B = new byte[N];
            byte[] C = new byte[N + 1];
            int a = random.Next((int)Math.Pow(10, N - 1), (int)(Math.Pow(10, N) - 1));
            int b = random.Next((int)Math.Pow(10, N - 1), (int)(Math.Pow(10, N) - 1));
            SetBinaryValue(A, a);
            SetBinaryValue(B, b);
            for (int i = C.Length - 1; i > 0; i--)
            {
                C[i] += (byte)(A[i - 1] + B[i - 1]);
                if (C[i] >= 10)
                {
                    C[i] = (byte)(C[i] % 10);
                    C[i - 1] = 1;
                }
            }
            Console.Write("  ");
            A.ToList().ForEach(i => Console.Write($"{ (int)i } "));
            Console.Write("\r\n+\r\n  ");
            B.ToList().ForEach(i => Console.Write($"{ (int)i } "));
            Console.Write("\r\n=\r\n");
            C.ToList().ForEach(i => Console.Write($"{ (int)i } "));
        }
        void SetBinaryValue(byte[] a, int n)
        {
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = (byte)(n / Math.Pow(10, N - i - 1) % 10);
            }
        }
    }
}
